package com.kaikeba.core.controller;

import com.baomidou.mybatisplus.core.metadata.PageList;
import com.github.pagehelper.PageInfo;
import com.kaikeba.core.annotation.ApiOperation;
import com.kaikeba.core.po.BaseEntity;
import com.kaikeba.core.po.ResponseBean;
import com.kaikeba.core.service.ICrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

public abstract class BaseController< S extends ICrudService<T>,T extends BaseEntity> {
    @Autowired
    protected  S service;
    @ApiOperation(value ="id",note = "根据id查询数据")
    @GetMapping("/edit/{id}")
    public T edit(@PathVariable("id") Long id){
        T entity = service.getById(id);
        afterEdit(entity);
        return entity;
    }
    @ApiOperation(value ="page",note = "根据分页查询数据")
    @PostMapping("/list-page")
    public PageInfo<T> listPage(T entity,
                                @RequestParam(name = "page",defaultValue = "1",required = false) Integer page,
                                @RequestParam(name = "row",defaultValue = "1",required = false) Integer row){
        PageInfo<T> result = service.listPage(entity, page, row);
        return result;
    }
    @ApiOperation(value = "list",note = "查询所有数据")
    @RequestMapping(value = "/list",method = {RequestMethod.POST,RequestMethod.GET})
    public List<T> list(T entity){
        List<T> list = service.list(entity);
        return list;
    }
    @ApiOperation(value = "save",note = "ID存在修改，不存在添加")
    @PostMapping("/save")
    public ResponseBean save(T entity){
        ResponseBean rm = new ResponseBean();
    try{
        beforeSave(entity);
        service.saveOrUpdate(entity);
        rm.setModel(entity);
    }catch (Exception e){
        e.printStackTrace();
        rm.setSuccess(false);
        rm.setMsg("保存失败");
    }
     return rm;
    }
    @ApiOperation(value = "delete",note = "根据ID删除数据")
    @GetMapping("delete/{id}")
    public ResponseBean delete(@PathVariable("id") Long id){
        ResponseBean rm = new ResponseBean();
        try{

            service.removeById(id);
            rm.setModel(id);
        }catch (Exception e){
            e.printStackTrace();
            rm.setSuccess(false);
            rm.setMsg("删除失败");
        }
        return rm;
    }
    /**
     * 在模板方法执行之前
     * @param entity
     */
    public void beforeSave(T entity){
        //该模块用户处理实体类
        //例如：例如权限管理等
    }

    /**
     * 在模板方法执行之后
     * @param entity
     */
    public void afterEdit(T entity){
        //该模块用户处理实体类
        //例如：例如权限管理等
    }


}


